<template>
  <el-dialog
    :title="!dataForm.id ? '新增课时' : '修改课时'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="onDialogClose"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="100px"
    >
      <!-- 课时标题 -->
      <el-form-item label="课时标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="请输入课时标题" />
      </el-form-item>

      <!-- 课时类型 -->
      <el-form-item label="课时类型" prop="lessonType">
        <el-select v-model="dataForm.lessonType" placeholder="请选择课时类型">
          <el-option label="视频" value="video" />
          <el-option label="图文" value="article" />
        </el-select>
      </el-form-item>
    </el-form>

      <el-form-item label="课时标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="AI知识库" />
      </el-form-item>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        title: '',
        lessonType: '',
        chapterId: null // 需要在父组件传入
      },
      dataRule: {
        title: [
          { required: true, message: '课时标题不能为空', trigger: 'blur' }
        ],
        lessonType: [
          { required: true, message: '课时类型不能为空', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    init(id, chapterId) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.dataForm.chapterId = chapterId;

        if (this.dataForm.id) {
          this.$http({
            url: `lessons/info/${this.dataForm.id}`,
            method: "get"
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm = data.data;
            }
          });
        }
      });
    },
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: `lessons/${!this.dataForm.id ? 'add' : 'update'}`,
            method: 'post',
            data: this.dataForm
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit('refreshDataList');
                }
              });
            } else {
              this.$message.error(data.msg || '保存失败');
            }
          });
        }
      });
    },
    onDialogClose() {
      this.$emit('dialogClosed');
    }
  }
};
</script>
